package com.chinadci.smartcommunitysystemreception.interceptors;


import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.chinadci.smartcommunitysystemreception.util.JWTUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Component
public class JwtInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if (request.getMethod().toUpperCase().equals("OPTIONS")){
            return true;
        }else {
        Map<String,Object> map=new HashMap<>();
        String token=request.getHeader("token");
        try {
            JWTUtils.Verify(token);
            return true;
        } catch (SignatureVerificationException e){
            e.printStackTrace();

            map.put("msg","无效签名");
        }catch (TokenExpiredException e){
            e.printStackTrace();
            map.put("msg","token过期");
        }catch (AlgorithmMismatchException e){
            e.printStackTrace();
            map.put("msg","token算法不一致");
        } catch (Exception e) {
            e.printStackTrace();
            map.put("msg","token无效");
        }

        map.put("state",false);
        String data= JSONObject.toJSONString(map);
        response.setContentType("application/json;charset=utf-8");

        try {
            response.getWriter().print(data);
        } catch (IOException e) {
            e.printStackTrace();
        }
            return false;
        }

    }
}
